package com.example.zhbj.base.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhbj.NewsDetailActivity;
import com.example.zhbj.R;
import com.example.zhbj.base.BaseMenuDetailPaper;
import com.example.zhbj.domain.NewsMenu;
import com.example.zhbj.domain.NewsTab;
import com.example.zhbj.global.GlobalConstans;
import com.example.zhbj.util.CacheUtil;
import com.example.zhbj.util.PrefUtils;
import com.example.zhbj.view.RefreshListView;
import com.example.zhbj.view.TopNewsViewPaper;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;

import java.util.ArrayList;
import android.os.*;

/**
 * 页签详情页，包含北京、中国、国际等页签
 * ViewPagerIndicator
 * 1.引入ViewPagerIndicator库
 * 2.解决v4冲突，用大的版本覆盖小的版本
 * 3.仿照sample中的程序进行拷贝SampleTabsDefault
 */
public class TabDetailPaper extends BaseMenuDetailPaper {

    /**
     * 当前页签数据
     */
    private NewsMenu.NewsTabData newsTabData;

    /**
     * 文本框对象
     */
     // private TextView view;

    /**
     * ViewPager对象
     */
    @ViewInject(R.id.vp_tab_detail)
    private TopNewsViewPaper mViewPaper;

    /**
     * 请求的URL地址
     */
    private String mUrl;

    /**
     * 保存头条新闻图片的集合
     */
    private ArrayList<NewsTab.TopNews> mTopNewsList;

    /**
     * TextView控件实例
     */
    @ViewInject(R.id.tv_title2)
    private TextView tvTitle;

    /**
     * Indicator控件实例
     */
    @ViewInject(R.id.indicator2)
    private CirclePageIndicator mIndicator;

    /**
     * ListView控件实例
     */
    @ViewInject(R.id.lv_list)
    private RefreshListView lvList;

    /**
     * 存储新闻列表的集合
     */
    private ArrayList<NewsTab.News> mNewsList;

    /**
     * 加载更多信息的Url
     */
    private String mMoreUrl;

    /**
     * 新闻详情的适配器
     */
    private NewsAdapter mNewsAdapter;

    /**
     * Handler对象
     */
    private Handler mHandler;

    public TabDetailPaper(Activity activity, NewsMenu.NewsTabData newsTabData) {
        super(activity);
        this.newsTabData = newsTabData;
        mUrl = GlobalConstans.SERVER_URL + newsTabData.url;
    }

    @Override
    public View initViews() {
        /*
        view = new TextView(mActivity);
        view.setTextSize(22);
        view.setTextColor(Color.RED);
        view.setGravity(Gravity.CENTER); // 居中显示
        view.setText("页签");
         */
        View view = View.inflate(mActivity,R.layout.paper_tab_detail,null);

        // 加载头条新闻的头布局
        View headerView = View.inflate(mActivity,R.layout.list_item_header,null);
        ViewUtils.inject(this,view);
        ViewUtils.inject(this,headerView);
        lvList.addHeaderView(headerView); // 给ListView添加头布局

        // 设置下拉刷新的监听
        lvList.setOnRefreshListener(new RefreshListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 刷新数据
                getDataFromServer();
            }

            @Override
            public void onLoadMore() {
                if (mMoreUrl != null){
                    getMoreDataFromServer();
                }else {
                    Toast.makeText(mActivity,"没有更多数据啦",Toast.LENGTH_SHORT).show();
                    lvList.onRefreshComplete();
                }
            }
        });

        // 设置点击事件
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 头布局也算位置，所以使用position时要将头布局个数减掉
                int headerViewsCount = lvList.getHeaderViewsCount();
                position -= headerViewsCount;
                NewsTab.News news = mNewsList.get(position);

                // 标记已读未读：将已读新闻id保存在sp中
                // key: "read_ids"
                // value: 11000,11001,11002...
                // 读取现有的id
                String readIds = PrefUtils.getString(mActivity, "read_ids", "");
                if (!readIds.contains(news.id)){
                    // 在现有id基础上追加新的id
                    readIds = readIds + news.id + ",";
                    // 保存最新的id集合
                    PrefUtils.putString(mActivity,"read_ids",readIds);
                }
                // 刷新ListView，全局刷新
                // mNewsAdapter.notifyDataSetChanged();
                // 刷新ListView，局部刷新
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_title3);
                tvTitle.setTextColor(Color.GRAY);

                // 跳到新闻详情页
                Intent intent = new Intent(mActivity, NewsDetailActivity.class);
                intent.putExtra("url",news.url); // 传递网页
                mActivity.startActivity(intent);
            }
        });

        return view;
    }

    @Override
    public void initData() {
        // view.setText(newsTabData.title); // 修改当前布局的数据
        String cache = CacheUtil.getCache(mActivity, mUrl);
        if (!TextUtils.isEmpty(cache)){
            // 有缓存
            processData(cache,false);
        }
        getDataFromServer();
    }

    /**
     * 从服务器中获取数据
     */
    private void getDataFromServer() {
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, mUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                processData(result,false);
                CacheUtil.setCache(mActivity,mUrl,result);

                // 隐藏下拉刷新控件
                lvList.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                e.printStackTrace();
                Toast.makeText(mActivity,s,Toast.LENGTH_SHORT).show();

                // 隐藏下拉刷新控件
                lvList.onRefreshComplete();
            }
        });
    }

    /**
     * 从服务器中获取下一页数据
     */
    private void getMoreDataFromServer() {
        HttpUtils utils = new HttpUtils();
        utils.send(HttpRequest.HttpMethod.GET, mMoreUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                processData(result,true);

                // 隐藏下拉刷新控件
                lvList.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                e.printStackTrace();
                Toast.makeText(mActivity,s,Toast.LENGTH_SHORT).show();

                // 隐藏下拉刷新控件
                lvList.onRefreshComplete();
            }
        });
    }

    private void processData(String result,boolean isMore) {
        Gson gson = new Gson();
        NewsTab newsTab = gson.fromJson(result, NewsTab.class);

        // 获取下一页的数据地址
        String more = newsTab.data.more;
        if (!TextUtils.isEmpty(more)){
            mMoreUrl = GlobalConstans.SERVER_URL + more;
        }
        else {
            mMoreUrl = null;
        }

        if (!isMore){
            // 初始化头条新闻数据
            mTopNewsList = newsTab.data.topnews;
            if (mTopNewsList != null){
                mViewPaper.setAdapter(new TopNewsAdapter());
                mIndicator.setViewPager(mViewPaper); // 将圆形指示器和viewpager绑定
                mIndicator.setSnap(true); // 快照展示方式
                mIndicator.onPageSelected(0); // 将圆点位置归零，保证圆点和页面同步
                mIndicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int i, float v, int i1) {

                    }

                    @Override
                    public void onPageSelected(int i) {
                        // 更新头条新闻的标题
                        tvTitle.setText(mTopNewsList.get(i).title);
                    }

                    @Override
                    public void onPageScrollStateChanged(int i) {

                    }
                });

                // 初始化首页标题
                tvTitle.setText(mTopNewsList.get(0).title);

                // 启动自动轮播效果
                if (mHandler == null){
                    mHandler = new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            int currentPos = mViewPaper.getCurrentItem();
                            if (currentPos < mTopNewsList.size() - 1){
                                currentPos++;
                            }else {
                                currentPos = 0; // 如果已经是最后一页，重新从第一页开始
                            }
                            mViewPaper.setCurrentItem(currentPos);
                            mHandler.sendEmptyMessageDelayed(0,2000);
                        }
                    };

                    // 发送延迟消息，启动自动轮播
                    mHandler.sendEmptyMessageDelayed(0,2000);
                }

                mViewPaper.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        switch (event.getAction()){
                            case MotionEvent.ACTION_DOWN:
                                mHandler.removeCallbacksAndMessages(null); // 移除消息，停止轮播
                                break;
                            case MotionEvent.ACTION_CANCEL:
                                // 事件取消：当按住头条新闻后，突然上下滑动，导致当前ViewPager事件被取消，而不响应抬起事件
                                mHandler.sendEmptyMessageDelayed(0,2000);
                                break;
                            case MotionEvent.ACTION_UP:
                                mHandler.sendEmptyMessageDelayed(0,2000);
                                break;
                            default:
                                break;
                        }
                        return false;
                    }
                });
            }

            /**
             * 初始化新闻列表数据
             */
            mNewsList = newsTab.data.news;
            if (mNewsList != null){
                mNewsAdapter = new NewsAdapter();
                lvList.setAdapter(new NewsAdapter());
            }
        }else {
            // 加载更多
            ArrayList<NewsTab.News> moreNews = newsTab.data.news;
            mNewsList.addAll(moreNews); // 追加更多数据
            // 刷新listview
            mNewsAdapter.notifyDataSetChanged();
        }

    }

    class TopNewsAdapter extends PagerAdapter{

        /**
         * xUtils中的BitmapUtils工具类
         */
        private BitmapUtils mBitmapUtils;

        public TopNewsAdapter() {
           mBitmapUtils = new BitmapUtils(mActivity);
           // 设置加载中的默认图片
           mBitmapUtils.configDefaultLoadingImage(R.drawable.pic_item_list_default);
        }

        @Override
        public int getCount() {
            return mTopNewsList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
            return view == o;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView view = new ImageView(mActivity);
            NewsTab.TopNews topNews = mTopNewsList.get(position);
            String topimage = topNews.topimage; // 图片的下载链接

            view.setScaleType(ImageView.ScaleType.FIT_XY); // 设置缩放模式：宽高匹配窗体
            /**
             * 1,根据url下载图片
             * 2.将图片设置给ImageView
             * 3.将图片作成缓存
             * 4.避免内存溢出
             * 由于工程量巨大，这里使用xUtils中的BitmapUtils里的api来完成这四个逻辑
             */
            mBitmapUtils.display(view,topimage);

            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 新闻列表适配器
     */
    class NewsAdapter extends BaseAdapter{

        /**
         * BitmapUtils工具类
         */
        private BitmapUtils mBitmapUtils;

        public NewsAdapter() {
            mBitmapUtils = new BitmapUtils(mActivity);
            mBitmapUtils.configDefaultLoadingImage(R.drawable.news_pic_default);
        }

        @Override
        public int getCount() {
            return mNewsList.size();
        }

        @Override
        public NewsTab.News getItem(int position) {
            return mNewsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null){
                convertView = View.inflate(mActivity,R.layout.list_item_news,null);
                holder = new ViewHolder();
                holder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title3);
                holder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);

                convertView.setTag(holder);
            }else {
                holder = (ViewHolder) convertView.getTag();
            }
            NewsTab.News info = getItem(position);
            holder.tvTitle.setText(info.title);
            holder.tvTime.setText(info.pubdate);
            mBitmapUtils.display(holder.ivIcon,info.listimage);

            // 判断已读未读
            String readIds = PrefUtils.getString(mActivity, "read_ids", "");
            if (readIds.contains(info.id)){
                holder.tvTitle.setTextColor(Color.GRAY);
            }
            else {
                holder.tvTitle.setTextColor(Color.BLACK);
            }
            return convertView;
        }
    }

    static class ViewHolder{
        public ImageView ivIcon;
        public TextView tvTitle;
        public TextView tvTime;
    }

}